package com.zztl.infiniteBand.ui.view

import android.content.Context
import android.graphics.Canvas
import android.support.v7.widget.AppCompatTextView
import android.util.AttributeSet


/**
 * @desc
 * @auth ${user}
 * @time 2018/9/14  10:15
 */
class CenterImgTextView : AppCompatTextView {
    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}

    constructor(context: Context) : super(context) {}

    override fun onDraw(canvas: Canvas) {
        val drawables = compoundDrawables
        if (drawables != null) {
            val drawableTop = drawables[1]
            for (i in drawables.indices) {
                val drawable = drawables[i]
                if (drawable != null) {
                    if (i == 0 || i == 2) {
                        val textWidth = paint.measureText(text.toString())
                        val drawablePadding = compoundDrawablePadding
                        var drawableWidth = 0
                        drawableWidth = drawable.intrinsicWidth
                        val bodyWidth = textWidth + drawableWidth.toFloat() + drawablePadding.toFloat()
                        canvas.translate((width - bodyWidth) / 2, 0f)
                    } else if (i == 1 || i == 3) {
                        val textHeight = paint.measureText(text.toString())
                        val drawablePadding = compoundDrawablePadding
                        val drawableHeight = drawableTop.intrinsicHeight
                        val bodyWidth = textHeight + drawableHeight.toFloat() + drawablePadding.toFloat()
                        canvas.translate(0f, (height - bodyWidth) / 2)
                    }
                }
            }
        }
        super.onDraw(canvas)
    }
}
